const express = require('express')
const http = require('http')
const cors = require('cors')
const dbRouter = require('./dataBase/api')
const dbManager = require('./dataBase/db')

const app = express()
const server = http.createServer(app)

// 添加CORS中间件
app.use(cors({
  origin: ['http://localhost:5174', 'http://127.0.0.1:5174'],
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}))

// 处理 preflight 请求
app.options('*', cors())

app.use(express.json())

// API路由
app.use('/api', dbRouter)

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('Error:', err)
  res.status(500).json({
    success: false,
    error: 'Internal Server Error',
    message: err.message
  })
})

// 404处理
app.use((req, res) => {
  res.status(404).json({
    success: false,
    error: 'Not Found',
    path: req.path
  })
})

const PORT = process.env.PORT || 3001

// 初始化数据库连接并启动服务器
const startServer = async () => {
  try {
    await dbManager.initializePools();
    server.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
      console.log(`Visit http://localhost:${PORT} to test the API`);
    });
  } catch (error) {
    console.error('Server startup failed:', error);
    process.exit(1);
  }
};

startServer();

// 优雅关闭
process.on('SIGTERM', async () => {
  try {
    await dbManager.closeAllPools();
    server.close(() => {
      console.log('Server closed');
      process.exit(0);
    });
  } catch (error) {
    console.error('Error during shutdown:', error);
    process.exit(1);
  }
});
